import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { message } from "antd";
const isBrowser = () => typeof window !== "undefined"; // 判断是否是浏览器

// 需要走服务端的接口
const service = axios.create({
  baseURL: process.env.API_URL, // 获取环境变量配置
  timeout: 10000, // 设置超时时间
}); // Request interceptor

// 创建一个请求队列
let pending: any = [];
const CancelToken = axios.CancelToken;
const removePending = (config: any) => {
  for (let p in pending) {
    if (pending[p].url === config.url + "&" + config.method) {
      pending[p].cancel("request canceled");
      pending.splice(p, 1);
    }
  }
};
// 自定义传入的参数
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    removePending(config);
    config.cancelToken = new CancelToken((c) => {
      pending.push({ cancel: c, url: config.url + "&" + config.method });
    });
    if (isBrowser()) {
      // config.headers["Authorization"] = authorization || "";
      config.url = "https://www.node.messln.cn" + config.url;
      // config.url = "http://localhost:7001" + config.url;
    }
    config.headers["Content-Type"] = "application/json";
    return config;
  },
  (error: any) => {
    Promise.reject(error);
  }
); // Response interceptors

service.interceptors.response.use(
  async (response: AxiosResponse) => {
    removePending(response.config);
    // pc段存储token
    console.log("请求结尾", response);
    if (isBrowser() && response.headers?.authorization) {
      localStorage.setItem("authorization", response.headers?.authorization);
    }
    const code = response.data.code;
    if (code === 401) {
      //   storage.remove('token');
      // setCookie(null, "token", "", {
      //   maxAge: 30 * 24 * 60 * 60,
      //   path: "/",
      // });
      if (typeof window !== "undefined") {
        // localStorage.clear();
        if (window.location.href.indexOf("login") != -1) {
          window.location.reload();
        } else {
          const config = {
            title: "系统提示",
            content: "登录状态已过期，您可以继续留在该页面，或者重新登录",
          };
        }
      }
    } else if (code === 6401) {
      //   storage.remove('token');
      // setCookie(null, "token", "", {
      //   maxAge: 30 * 24 * 60 * 60,
      //   path: "/",
      // });
      const config = {
        title: "系统提示",
        content: "登录状态已过期，您可以继续留在该页面，或者重新登录",
      };
      //   modal.confirm(config);
      return false;
    } else if (code === 400 || code === 403) {
      if (typeof window !== "undefined") {
        message.error(response.data.msg);
      }
    } else {
      return response.data;
    }
  },
  (error: any) => {
    console.log("请求错误error", error);
    if (error.message == "Network Error") {
      if (typeof window !== "undefined") {
        // message.error('服务器连接异常，请检查服务器！');
      }
      return;
    } else if (error.code === "ERR_CANCELED") {
      // message.error('多次请求');
      return;
    } else {
      return Promise.reject(error);
    }
  }
);

export default service;
